//
//  WebViewCell.m
//  JGShop
//
//  Created by BB on 2017/9/23.
//  Copyright © 2017年 ike. All rights reserved.
//

#import "WebViewCell.h"
#import "AppHeader.h"

@implementation WebViewCell {
    NSString *htmlStr;
    NSString *HTTPStr;
    // 默认 -12
    __weak IBOutlet NSLayoutConstraint *webView_left;
    // 默认 -8
    __weak IBOutlet NSLayoutConstraint *webView_top;
    BOOL isDocx;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    _webView.opaque =NO;
    _webView.backgroundColor =[UIColor clearColor];
}

- (void)loadHTTPWeb:(NSString*)URLString {
    _webView.scalesPageToFit = YES;
    _webView.userInteractionEnabled =NO;
    URLString =[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if (![HTTPStr isEqualToString:URLString]) {
        HTTPStr =URLString;
        [self downloadFileWithUrl:URLString];
    }
}

- (void)loadHTMLString:(NSString *)htmlString {
    _webView.scalesPageToFit = NO;
    _webView.userInteractionEnabled =YES;
    NSString *html = [NSString stringWithFormat:@"<html><style>img {max-width:100%%;}</style><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><meta name=\"MobileOptimized\" content=\"304\"><body><div id=\"viewport\"; name=\"viewport\">%@</div></body></html>", htmlString];
    
    if (![htmlStr isEqualToString:html]) {
        htmlStr =html;
        [self.webView loadHTMLString:html/*[WebViewCell trimmedStringWithSpecialString:htmlString]*/ baseURL:nil];
    }
}

#pragma mark =======>webViewDelegate<==========
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if (isDocx) {
        webView_left.constant =-KScreenWidth*0.2;
        webView_top.constant =-60;
    } else {
        webView_left.constant =-12;
        webView_top.constant =-10;
    }
    CGRect frame = webView.frame;
    frame.size.height = 1;
    webView.frame = frame;
    CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    webView.bounds = CGRectMake(0, 0, KScreenWidth, frame.size.height);
    
    if (_loadBlock) {
        _loadBlock(YES, CGRectGetHeight(webView.frame));
    }

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    if (_loadBlock) {
        _loadBlock(NO, 0.0);
    }
}

- (void)loadWebViewTypeBlock:(LoadWebBlock)newBlock {
    self.loadBlock =newBlock;
}


//去除HTML标签对
+ (NSString *)trimmedStringWithSpecialString:(NSString*)string {
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n|\r" options:0 error:nil];
    
    NSString *trimmedString =[regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];//替换所有html和换行匹配元素为"-"
    return trimmedString;
}

/**
 *  html字符串替换
 *
 *  @param string html源代码
 *
 *  @return 新的html
 */
+ (NSString *)htmlSpecialChars:(NSString*)string {
    NSString * html =string;
    if (isStringEmpty(html)) {
        return @"";
    }
    html =[html stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    html = [html stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    html = [html stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"&amp;nbsp;" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"&amp;ldquo;" withString:@"“"];
    html = [html stringByReplacingOccurrencesOfString:@"&amp;rdquo;" withString:@"”"];
    html = [html stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return html;
}


/**
 *  下载
 *
 *  @param urlStr 下载路径
 */
-(void)downloadFileWithUrl:(NSString*)urlStr {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSString *fileName =[[urlStr componentsSeparatedByString:@"/"] lastObject];
    //*
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        /// 保证该文件夹存在(文件的上层文件夹)
        NSString *path =[NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@", DefaultFileName]];
        if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        }
        /// 告诉AFNetworking缓存到此处(连后缀名)
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", DefaultFileName, fileName]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error) {
            NSString *errorFilePath =[NSString stringWithFormat:@"%@/%@", [self creactPath], fileName];
            if ([[NSFileManager defaultManager] fileExistsAtPath:errorFilePath]) {
                [[NSFileManager defaultManager] removeItemAtPath:errorFilePath error:nil];
            }
        } else {
            if ([filePath.absoluteString hasSuffix:@".rar"]) {
                [AppToast showFileWithString:@"无法打开.rar文件"];
                return;
            }
            isDocx =[filePath.absoluteString hasSuffix:@".docx"]?YES:NO;
            [self.webView loadRequest:[NSURLRequest requestWithURL:filePath]];
        }
    }];
    [downloadTask resume];
    // */
}

//创建路径
-(NSString *)creactPath {
    NSString *path =[NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@", DefaultFileName]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return path;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


@end
